package com.yanqu.road.server.manger.activity.snowgarden;

import com.yanqu.road.dao.impl.player.ServerActivityMallDayBuyDaoImpl;
import com.yanqu.road.entity.activity.ServerActivityMallDayBuyData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MallDayBuyUserMallInfo {
    private int activityId;
    private long userId;
    private int activityDay;
    //key:mallId
    private Map<Integer, ServerActivityMallDayBuyData> mallDayBuyDataMap = new ConcurrentHashMap<>();

    public MallDayBuyUserMallInfo(int activityId, long userId, int activityDay) {
        this.activityId = activityId;
        this.userId = userId;
        this.activityDay = activityDay;
    }

    public void addBuyData(ServerActivityMallDayBuyData buyData) {
        mallDayBuyDataMap.put(buyData.getMallId(), buyData);
    }

    public ServerActivityMallDayBuyData getUserDayMallInfoNewIfNull(int mallId) {
        ServerActivityMallDayBuyData dayBuyData = mallDayBuyDataMap.get(mallId);
        if (dayBuyData == null) {
            synchronized (mallDayBuyDataMap){
                dayBuyData = mallDayBuyDataMap.get(mallId);
                if (dayBuyData == null) {
                    dayBuyData = new ServerActivityMallDayBuyData(activityId, mallId, this.activityDay, userId);
                    mallDayBuyDataMap.put(mallId, dayBuyData);
                }
            }
        }
        return dayBuyData;
    }

    public void addMallBuy(int mallId) {
        ServerActivityMallDayBuyData dayBuyData = getUserDayMallInfoNewIfNull(mallId);
        dayBuyData.addBuyNum();
    }

    public boolean isUserTodayBuyMall(int mallId) {
        ServerActivityMallDayBuyData dayBuyData = mallDayBuyDataMap.get(mallId);
        if (dayBuyData == null) {
            return false;
        }
        if (dayBuyData.getBuyCount() > 0) {
            return true;
        }
        return false;
    }

    public void save() {
        List<ServerActivityMallDayBuyData> tempDataList = new ArrayList<>();
        synchronized (mallDayBuyDataMap) {
            tempDataList.addAll(mallDayBuyDataMap.values());
        }

        for (ServerActivityMallDayBuyData buyData : tempDataList) {
            if (buyData.isInsertOption()) {
                new ServerActivityMallDayBuyDaoImpl().add(buyData);
            } else if (buyData.isUpdateOption()) {
                new ServerActivityMallDayBuyDaoImpl().update(buyData);
            }
        }
    }

    public ServerActivityMallDayBuyData getDayBuyData(int mallId) {
        return mallDayBuyDataMap.get(mallId);
    }
}
